import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:wallpaper/api/manyACG.dart';
import 'package:wallpaper/components/images/image_list.dart';
import 'package:wallpaper/components/input/my_search_input.dart';
import 'package:wallpaper/model/image_base.dart';

class ManyacgSearch extends StatefulWidget {
  final int r18;
  const ManyacgSearch({super.key, required this.r18});

  @override
  State<ManyacgSearch> createState() => _ManyacgSearchState();
}

class _ManyacgSearchState extends State<ManyacgSearch> {
  // 使用final列表，只修改内容不替换引用
  final List<ImageBase> imgs = [];
  final TextEditingController controller = TextEditingController();
  final Set ids = {}; // 使用final集合
  bool isLoading = false;
  int page = 1;
  final int num = 35; // 常量用final修饰

  Future<void> getManyAcgRandomImages() async {
    if (!mounted || isLoading) return;
    setState(() {
      isLoading = true;
    });
    try {
      Response res = await getManyAcgSearch(
        page: page,
        page_size: num,
        r18: widget.r18,
        limit: num,
        keyword: controller.text,
      );
      List data = res.data['data'];
      for (var item in data) {
        // 修复：使用id作为去重标识（原代码误用height导致去重失效）
        if (ids.contains(item['pictures'][0]['id'])) continue;
        ids.add(item['pictures'][0]['id']);
        
        // 过滤avif格式
        String largePathResult = item['pictures'][0]['regular'];
        if (largePathResult.contains('.avif')) continue;
        
        String smallPathResult = item['pictures'][0]['thumbnail'];
        if (smallPathResult.contains('.avif')) {
          smallPathResult = largePathResult;
        }
        
        imgs.add(ImageBase(
          largePath: largePathResult,
          smallPath: smallPathResult,
          width: item['pictures'][0]['width'],
          height: item['pictures'][0]['height'],
          tags: item['tags'].join(' '),
        ));
      }
    } catch (e) {
      debugPrint('加载图片错误: $e');
    } finally {
      if (mounted) {
        setState(() {
          isLoading = false;
        });
      }
    }
  }

  // 提取搜索提交逻辑为独立方法
  void _handleSearchSubmitted(String value) {
    FocusScope.of(context).unfocus(); // 更简洁的失焦方式
    imgs.clear();
    ids.clear();
    page = 1;
    getManyAcgRandomImages();
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context).colorScheme;
    
    // 使用RepaintBoundary隔离重绘区域
    return RepaintBoundary(
      child: Scaffold(
        resizeToAvoidBottomInset: false,
        appBar: AppBar(
          title: const Text(''),
          toolbarHeight: 0,
          elevation: 0,
          leading: null,
          backgroundColor: theme.primaryContainer,
          surfaceTintColor: theme.primaryContainer,
        ),
        body: Column(
          children: [
            // 搜索框独立封装并使用RepaintBoundary
            const RepaintBoundary(
              child: _SearchInputWidget(),
            ),
            Expanded(
              child: ImageList(
                imageList: imgs,
                isLoading: isLoading,
                isWaterfallFlow: true,
                onImageBottomLoading: () {
                  page += 1;
                  getManyAcgRandomImages();
                },
                onImageListRefresh: () {
                  imgs.clear();
                  ids.clear();
                  page = 1;
                  getManyAcgRandomImages();
                },
              ),
            ),
          ],
        ),
      ),
    );
  }
}

// 将搜索框提取为独立无状态组件，减少重建范围
class _SearchInputWidget extends StatelessWidget {
  const _SearchInputWidget();

  @override
  Widget build(BuildContext context) {
    // 通过上下文获取父组件状态
    final parentState = context.findAncestorStateOfType<_ManyacgSearchState>()!;
    
    return MySearchInput(
      controller: parentState.controller,
      onSubmitted: (v) => parentState._handleSearchSubmitted(v),
    );
  }
}
    